package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.Dept;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService {
    //完成分页条件查询
    @Autowired
    private EmpMapper empMapper;
    @Override
    public PageResult<Clazz> pageQuery(int page, int pageSize, String name, LocalDate begin, LocalDate end) {
        LambdaQueryWrapper<Clazz> queryWrapper=new LambdaQueryWrapper<Clazz>()
                .like(name!= null, Clazz::getName, name)
                .between(begin != null && end != null, Clazz::getBeginDate, begin, end);
        Page<Clazz> pageInfo=new Page<Clazz>(page,pageSize);
        page(pageInfo,queryWrapper);
        //处理班主任名字展示
        pageInfo.getRecords().forEach((Clazz clazz)-> {
            //从emp表中获取姓名数据赋值给masterName属性
            //先获取班主任的id.
            Emp emp = empMapper.selectById(clazz.getMasterId());
            //判断此班级有无班主任
            if(emp!=null){
                //给记录数据中的masterName属性赋值.
                clazz.setMasterName(emp.getName());
            }
            //修改状态信息
            if (LocalDate.now().isBefore(clazz.getBeginDate())){
                clazz.setStatus("未开班");
            }else if(LocalDate.now().isAfter(clazz.getEndDate())){
                clazz.setStatus("已结课");
            }else{
                clazz.setStatus("已开班");
            }
        });
        return new PageResult<>(pageInfo.getTotal(),pageInfo.getRecords());
    }

    @Override
    public void add(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazz.setCreateTime(LocalDateTime.now());
        save(clazz);
    }

}
